package com.rocpenghua.codec;

import com.rocpenghua.codec.sm4Simple.HexUtil;
import com.rocpenghua.codec.sm4Simple.SM4;
import com.rocpenghua.codec.sm4Simple.SM4Context;

/**
 * Describe:
 * Created by AlexP on 2022/4/18.
 */
public class SM4SimpleUtil extends HexUtil {
    public static String SM4_KEY_VALUE = "qazQAZ!@#123WSX*";
    public static String encrypt(String plainText, String secretKey) {
        try {
            SM4Context ctx = new SM4Context();
            ctx.isPadding = true;
            ctx.mode = 1;
            byte[] keyBytes = null;
            if (secretKey.length() < 32) {
                keyBytes = hexToByte(getHexString(secretKey.getBytes()));
            } else {
                keyBytes = hexStringToBytes(secretKey);
            }
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes("UTF-8"));
            return getHexString(encrypted);
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }
    public static String decrypt(String cipherTextString, String secretKey) {
        try {
            SM4Context ctx = new SM4Context();
            ctx.isPadding = true;
            ctx.mode = 0;
            byte[] keyBytes = null;
            if (secretKey.length() < 32) {
                keyBytes = hexToByte(getHexString(secretKey.getBytes()));
            } else {
                keyBytes = hexStringToBytes(secretKey);
            }
            byte[] cipherText = hexToByte(cipherTextString);
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, cipherText);
            return new String(decrypted);
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }
}